import java.util.Arrays;
import java.util.Comparator;
import java.util.PriorityQueue;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: WJW
 * Date: 2024-07-24
 * Time: 15:13
 */
// 求堆中的最小K个数
class Imp implements Comparator<Integer>{

    @Override
    public int compare(Integer o1, Integer o2) {
        return o2.compareTo(o1);
    }
}
public class Test {

    public int[] smallestK(int[] array, int k){
        int[] ret = new int[k];
        if(array == null || k <= 0){
            return ret;
        }
       // PriorityQueue<Integer> priorityQueue = new PriorityQueue<>(new Imp());

        PriorityQueue<Integer> priorityQueue = new PriorityQueue<>(new Comparator<Integer>() {
            @Override
            public int compare(Integer o1, Integer o2) {
                return o2.compareTo(o1);
            }
        });
        //1.建立大小为k的大根堆O(K*logK)
        for (int i = 0; i < k; i++) {
            priorityQueue.offer(array[i]);
        }

        //2.遍历剩下的元素（N-K)*logK
        for (int i =k ; i < array.length ; i++) {
            int top = priorityQueue.peek();
            if(array[i]<top){
                priorityQueue.poll();
                priorityQueue.offer(array[i]);
            }
        }

        for(int i = 0;i<k;i++){
            ret[i] = priorityQueue.poll();

        }
        return ret;
    }

    public static void main(String[] args) {
        PriorityQueue<Integer> priorityQueue = new PriorityQueue<>();
        int[] array = {10,3,15,7,19,9};

        //相当于向上调整建小根堆 O(n*logn)
        for(int i = 0;i< array.length;i++){
            priorityQueue.offer(array[i]);
        }

        int k = 3;
        int[] ret = new int[k];
        //k*logN
        for(int i = 0;i<k;i++){
            ret[i] = priorityQueue.poll();
        }

        System.out.println(Arrays.toString(ret));
    }
}
